# -*- coding: utf-8 -*-
import scrapy
from scrapy.http.request import Request
from scrapy.http.request.form import FormRequest

from scrapyLogin.items import ScrapyloginItem


class GiteeloginSpider(scrapy.Spider):
    name = 'giteeLogin'
    allowed_domains = ['gitee.com']
    #start_urls = ['http://gitee.com/']
    
    def start_requests(self):
        url = "https://gitee.com/login"
        yield Request(url)
        
    def parse(self, response):
        #1 获取到token
        csrfToken = response.xpath("//meta[@name='csrf-token']/@content").extract()[0]
        print("登录Token：",csrfToken)
        
        #2 组装登录参数
        loginData = {
            "authenticity_token":csrfToken,
            #登录成功后，进入的页面
            "redirect_to_url":"",
            "user[login]":"改成你自己的登录账号",
            "user[password]":"改成你自己的账户密码",
            "user[remember_me]":"0",
            "commit":"登 录",
        }
        
        return [FormRequest.from_response(response,url='https://gitee.com/login',method="post",formdata=loginData,callback=self.next)]
    
    def next(self,response):
        print("------------------------")
        print("------------------------")
        print("title = ",response.xpath("//title/text()")[0])
        
        item = ScrapyloginItem()
        #用户下所有项目的页面链接
        item["projectsUrl"] = response.xpath("//div[@class='header user-projects']/a/@href").extract()[0]
        print("------------------------")
        print("------------------------")
        return item
    